<?php 
class BlogAction extends Action{
    function _initialize() {
		
	 }
	public function index(){
	    $db_prefix  =  C('DB_PREFIX');
	    $followCount = M('weibo_follow')->where('`uid` = '.$this->mid.' AND `type` = 0')->count();
	    //$fuids = M('weibo_follow')->where('uid='.$this->mid)->findAll();
		$map ="status=1 ";
		if($followCount){
		   $weibo = M('weibo');
		   $map.=" AND ( uid IN (SELECT fid FROM {$db_prefix}weibo_follow WHERE uid={$this->mid} AND type=0))";
		   $count= $weibo->where($map)->count();
		   $p = new Page ( $count, 10 );
		   $list =  $weibo->where($map)->limit($p->firstRow.','.$p->listRows)->order('ctime DESC')->findAll();
		   foreach ($list as $k => $v) {
	          if($list[$k]['tag']){
	            $list[$k]['tag']= explode(',',$list[$k]['tag']);
		      }
           }
		   $page = $p->show ();
	       $this->assign ( "page", $page );
		}
		//echo $count;
		
	 	$this->assign ( 'list',$list);
	 	$this->setTitle ( '我关注的博客' );
 	    $this->display();
	 }
    public function myblog(){
	 $db_prefix  =  C('DB_PREFIX');
	 //$cmap="uid='{$this->mid}'";
	 $map="uid='{$this->mid}' and status!=-1 ";
	 if($_GET['k']){
	   $search_key   =  $this->__getSearchKey ();
	   $keyinfo = M('tag')->where("tag_name='{$search_key}'")->find();
	   if ($keyinfo) {
		$list = M('weibo_tag')->where("tag_id=".$keyinfo['tag_id'])->field('weibo_id')->findAll();
			
		$weibo_ids = getSubByKey($list, 'weibo_id');
		//$cmap.="AND weibo_id in (".implode(',',$weibo_ids).")";
	    $map.="AND weibo_id in (".implode(',',$weibo_ids).")";
	   }
	 }
 	 $weibo = M( 'weibo' );
 	 $count= $weibo->where($map)->count();
	 $p = new Page ( $count, 10 );
 	 $list=$weibo->where($map)->limit($p->firstRow.','.$p->listRows)->order('ctime DESC')->findAll();
	 foreach ($list as $k => $v) {
	    if($list[$k]['tag']){
	    $list[$k]['tag']= explode(',',$list[$k]['tag']);
		}
     }
 	 $page = $p->show ();
	 $this->assign ( "page", $page );
	 //echo $page;
	 //print_r($list);
 	 $this->assign('list',$list);
 	 $this->setTitle ( '文章列表' );
 	 $this->display('index');
     }
     
	public function  add(){
	 //$this->assign('list',$list);
	 $this->getCreateWeibo_id();
 	 $this->setTitle ( '写文章' );
 	 $this->display();		
	}
    public function  edit(){
	 
    	$id  = empty($_GET['id'])? 0:intval($_GET['id']);
	   
	     
	      $map['weibo_id'] = $_SESSION['tempid']=$id;
	      $map['uid']=$this->mid;
	      
	      $weibolist = M('weibo')->where($map)->find();
	      
	      if(!$weibolist){
		     $this->error('您查看的页面不存在，或者已经删除');
			 exit;
		  }
		  if($weibolist['blog_id']){
			 $blist = M('blog')->field('post')->where('blog_id='.$weibolist['blog_id'])->find();
			 $weibolist['content']=$blist['post'];
		  }
	       $weibolist['tag'] =  $this->_gettag($map['weibo_id']);
	      
	       $this->assign('bloglist',$weibolist);
	            
		     
		  $this->setTitle ( '编辑文章' );
 	      $this->display();	
	      
	}
	//转载博客
	public function  reship(){
	 
    	$id  = empty($_GET['id'])? 0:intval($_GET['id']);
		$this->getCreateWeibo_id();
	    if($id){	     
	      $weibo = M('weibo');
	      $weibolist=$weibo->where('weibo_id='.$id)->find();
	      //print_r($weibolist);
	      if($weibolist){
		     if($weibolist['blog_id']){
			    $blog_post=M('blog')->field('post')->where('blog_id='.$weibolist['blog_id'])->find();
				//print_r($blog_post);
				$weibolist['content']=$blog_post['post'];
			 }
	         $weibolist['tag'] =  $this->_gettag($id);
	      
	         $this->assign('bloglist',$weibolist);
	         $this->setTitle ( '转载文章' );
 	         $this->display();		
	      }else{
	         $this->error('您查看的页面不存在，或者已经删除');
	      }
	      
	    }else{
	     $this->error('您查看的页面不存在，或者已经删除');
	    }
		
	}
	public function doDel(){      //删除博客 未设置删除评论
	 $id = empty($_POST['wb_id'])?0:intval($_POST['wb_id']);
	 
	 $map['weibo_id'] = $id;
	 $map['uid']      = $this->mid;
	 $weibo = M('weibo')->where($map)->find();
	 if($id==0 || !$weibo){
	    echo -1;     //不存在或者已经删除
		return ;
	 }
	 //删除博文详细内容
	 if($weibo['blog_id']){
	     M('blog')->where('blog_id='.$weibo['blog_id'])->delete();
	 }
	 //删除附件
	 $attach = M('attach');
	 $attachlist = $attach->field('path')->where("weibo_id ={$map['weibo_id']} and userId={$this->mid}")->findAll();
	 
	 for($i=0;$i<count($attachlist);$i++){
		@unlink(SITE_PATH.'/'.$attachlist[$i]['path']);
	 }
	 $attach->where("weibo_id ={$map['weibo_id']} and userId={$this->mid}")->delete();
	 //删除标签
	 M('weibo_tag')->where($map)->delete();
	 echo ($rel=M('weibo')->where($map)->delete())?1:0;
	 
	}
	
	public function checkall(){
		if($_POST['content']==''){
		$this->error('内容不能为空');		
		}elseif($_POST['tag_names']==''){
		$this->error('至少填写一个标签');
		
		}else{
		$this->saveform();
		}
		
	}
	//关注人
    public function follow(){
	    
    	if($_POST['type']=='dofollow'){
    		echo D('Follow')->dofollow( $this->mid,intval($_POST['uid']) );
    	}else{
    		echo D('Follow')->unfollow( $this->mid,intval($_POST['uid']) );
    	}
    }
	
	//保存文章
	protected function saveform(){
	    $data = array();
		if($_POST['weibo_id']){    //编辑文章
		
		$data['weibo_id'] = empty($_POST['weibo_id']) ? 0:  intval($_POST['weibo_id']);
		$blog_id = empty($_POST['blog_id']) ? 0:  intval($_POST['blog_id']);
		$blog = $this->_edblog($blog_id,$_POST['content']);      //编辑博客正文

		$strtags = $this->ed_weibo_tag(t($_POST['tag_names']),$data['weibo_id']); // 编辑标签
		$data['tag']         =    $strtags;
		$data['title']       =    t($_POST['title']);
		$data['content']     =    $blog['content'] ;
		$data['blog_id']     =    $blog['blog_id'];
		$data['utime']       =    time();
		$data['status']      =    intval($_POST['status']);
		
		$weibocont = M('weibo')->save($data);
		
		if($weibocont){
		    $_SESSION['tempid'] = NULL;
		    unset($_SESSION['tempid']);
			$this->success('更新成功');
			
		}else{
			
			$this->error('更新失败');
		}
	   }elseif($_POST['weibo_uid']){    //转载文章
	     $weibo_uid   =    intval($_POST['weibo_uid']);
	     $from_uid    =    intval($_POST['from_uid']);
         if($from_uid==$this->mid  ||  $weibo_uid==$this->mid){
		    $this->error('不能转载自己的文章');
		  }
		$blog    = $this->_addblog($_POST['content']);      //编辑博客正文
		$strtags = $this->add_weibo_tag(t($_POST['tag_names']),$_SESSION['tempid']);		
		$data['uid']         =    $this->mid;
		$data['uname']       =    $this->user['uname'];
		$data['tag']         =    $strtags;
		$data['title']       =    t($_POST['title']);
		$data['content']     =    $blog['content'];
		$data['from_uid']    =    $from_uid;
		$data['from_uname']  =    t($_POST['from_uname']);
		$data['blog_id']     =    $blog['blog_id'];
		$data['utime']       =    time();
		$data['ctime']       =    time();
		$data['status']      =    intval($_POST['status']);
		
		$weibo_id = M('weibo')->where('weibo_id='.$_SESSION['tempid'])->save($data);
		
		if($weibo_id){
		    $_SESSION['tempid'] = NULL;
		    unset($_SESSION['tempid']);
			$this->success('转载成功');
			
		}else{
			$this->error('转载失败');
		}
	   
	   }else{    //写文章
		if(empty($_SESSION['tempid'])){$this->error('临时id丢失');}
		
		$blog = $this->_addblog($_POST['content']);      //编辑博客正文
		$strtags = $this->add_weibo_tag(t($_POST['tag_names']),$_SESSION['tempid']);
		
		$data['weibo_id']    =    $_SESSION['tempid'];
		$data['uid']         =    $this->mid;
		$data['uname']       =    $this->user['uname'];
		$data['tag']         =    $strtags;
		$data['title']       =    t($_POST['title']);
		$data['content']     =    $blog['content'] ;
		$data['from_uid']    =    $this->mid;
		$data['from_uname']  =    $this->user['uname'];
		$data['blog_id']     =    $blog['blog_id'];
		$data['utime']       =    time();
		$data['ctime']       =    time();
		$data['status']      =    intval($_POST['status']);
		//echo $_POST['tag_names'];
		//exit();
		//$data['tag']            =    t($_POST['tag_names']);
		//print_r($data);
		$res = M('weibo')->save($data);
		
		
	   if($res){
	        $_SESSION['tempid'] = NULL;
		    unset($_SESSION['tempid']);
			$this->success('发表成功');
			
		}else{
			
			$this->error('发表失败');
		}
	  }
	}
	protected function _edblog($blog_id,$post){
	      $blog  = array();
		  $data['uid']         =    $this->mid;
	      $data['post']        =    keyWordFilter(strip_tags($post,'<p>,<a>,<strong>,<em>,<br>,<pre>,<img>,<u>,<del>,<ol>,<ul>,<li>'));
		  $this->_localImgParse($data['post']);//删除编辑器中未使用的的图片
		  
		  if(get_str_length($data['post'])>400){
		      if($blog_id){
		         M('blog')->where('blog_id='.$blog_id)->save($data);
				 $blog['blog_id'] = $blog_id;
			  }else{
			     $blog['blog_id'] = M('blog')->add($data);
			  }
		      
		      $blog['content'] = blog_summary($data['post'],400).".....";
		      return $blog;
		  }else{
		      M('blog')->where('blog_id='.$_POST['blog_id'])->delete();
		      $blog['blog_id'] =  0;
		      $blog['content'] =  $data['post'];
		      return $blog;
		  }
	}
	protected function _addblog($post){
	      $blog  = array();
		  $data['uid']        =   $this->mid;
	      $data['post']       =    keyWordFilter(strip_tags($post,'<p>,<a>,<strong>,<em>,<br>,<pre>,<img>,<u>,<del>,<ol>,<ul>,<li>'));
		  
		  $this->_localImgParse($data['post']);//删除编辑器中未使用的的图片
		  if(get_str_length($data['post'])>400){
		      $blog['blog_id'] = M('blog')->add($data);

		      $blog['content'] =blog_summary($data['post'],400).".....";
		      return $blog;
		  }else{
		      $blog['blog_id'] =  0;
		      $blog['content'] =  $data['post'];
		      return $blog;
		  }

	}
	//获得编辑器实际使用的图片
	private function _localImgParse($body)
	{	
		preg_match_all( "/<img.[^>]*?(src|SRC)=\"[\"|'| ]{0,}([^>]*\\.(gif|jpg|jpeg|bmp|png))([\"|'|\\s]).*[\\/]?>/isU",stripslashes($body) , $info );
		
		$info = array_unique($info[2]);
	     //print_r($info);
		$str = '';
		if(is_array($info))
		{
			foreach($info as $d)
			{//echo $d;
			 if (substr($d,0,4) != 'http')  //非本地连接不管
			 {  //echo 'fadsfadsfsadsdsadasdasdas';
				if(substr($d,0,13) == 'data/uploads/')  //如果不是 data/uploads/开头不管
				{
					$path = pathinfo($d);
					if(substr($path['basename'],0,2) == 't_') {$d = $path['dirname'].'/'. substr($path['basename'],2,99);}//如果是缩略图
				}
			 }	
			 $str .= '\''.$d.'\',';
			}
			
			$str = substr($str,0,-1); //去掉逗号
			if($str){ $where = "`path` not in ($str) and"; } //如果存在 就加限制
			$result = M('attach')->field('id, path')->where("$where  userId  = {$this->mid} and weibo_id = {$_SESSION['tempid']}")->findAll(); //获取到编辑器没有使用的

			if(is_array($result))
			{   
			    $attach_path = getSubByKey($result,'path');
			    $attach_id = getSubByKey($result,'id');
				/*print_r($result);
				print_r($attach_path);
				print_r($attach_id);
				exit();*/
				$attach  =M('attach');
				for($i=0;$i<count($attach_path);$i++){
				 @unlink(SITE_PATH.'/'.$attach_path[$i]);
				}
				$attach->where("id in (".implode(',',$attach_id).")")->delete();
				
				//foreach($result as $d) //全部搞定
				//{
				//	M('attach')->where("id ={$d['id']} AND userId={$this->mid}")->delete();
				//}
			}
		}
	}
	
	/*获取一个可用的临时ID
	$tempid $_SESSION['tempid'] 临时的 weibo_id
	
	*/
	protected function getCreateWeibo_id(){
        $map['uid']     =  $this->mid;
        $map['status']  =  -1;	
        $weibo =M('weibo');		
	    $res =$weibo->field('weibo_id')->where($map)->find();
		if(empty($res)){
		$map['from_uname'] = $map['uname']   =  $this->user['uname'];
		$map['from_uid']   = $this->mid;
		   $tempid =$_SESSION['tempid']= $weibo->add($map);
		}else{
		   $tempid =$_SESSION['tempid']=$res['weibo_id'];
		}
		//echo $tempid;
	}
//编辑weibo_tag  博客  标签   关联表数据
	protected function ed_weibo_tag($tag,$weibo_id){
		
		$taglist = array_unique(array_filter(explode('×', keyWordFilter($tag))));       //将字符串转换为 数组  并且删除  值为空的元素和重复的数组元素
		$strtags = implode(',',array_slice($taglist,0,5));
		//print_r($taglist);
		$del_ids = $add_ids ='';
		$weibo_tag = M('weibo_tag');
		$map['uid']       =   $this->mid;
		$map['weibo_id']   =   $weibo_id;
		$old_tag_ids = $weibo_tag->field('tag_id')->where($map)->findAll();   //获取指定博客 的 所有标签的 tag_id
		$old_tag_ids = getSubByKey($old_tag_ids,'tag_id');
		$new_tag_ids=array();   //提交的所有标签的 tag_id
	    foreach ($taglist as $k=>$v){	
			$new_tag_ids[]=$this->_checktag($v);
		}
		$del_ids=implode(',',array_diff($old_tag_ids,$new_tag_ids)); //用户删除的 tag_id   implode()
		$add_ids=array_diff($new_tag_ids,$old_tag_ids); //用户添加的 tag_id   sort()
		if($del_ids){
		   $weibo_tag->where("uid={$this->mid} and tag_id in ({$del_ids})")->delete();
		   M('tag')->setDec('num',"tag_id in ({$del_ids})",1); 
		}
		//echo $tag->getLastSql();
		if($add_ids){
		   foreach($add_ids as $d){
		       $map['tag_id'] =$d;
		       $weibo_tag->add($map);  
		   }
		}
		return $strtags;
		
	}
	//插入weibo_tag  博客  标签   关联表数据
	protected function add_weibo_tag($tag,$weibo_id){
		
		$taglist = array_unique(array_filter(explode('×', keyWordFilter($tag))));    
		$strtags = implode(',',array_slice($taglist,0,5));
		//exit;
		$weibo_tag = M('weibo_tag');
		$data['uid']       =   $this->mid;
		$data['weibo_id']   =   $weibo_id;
		//$data['ctime']     =   time();
		$weibo_tag_id=array();
		foreach ($taglist as $k=>$v){
			//echo $v;
			$data['tag_id']=$this->_checktag($v);
			$weibo_tag_id[]=$weibo_tag->add($data);
		}
		return $strtags;
		
	}
	
	//判断标签 是否存在      并且返回 标签主键tag_id 的值
	protected function _checktag($tagname){
		//echo $tagname;
		$tag = M('tag');
		$tag_id=$tag->where("tag_name='$tagname'")->getField('tag_id');
		if($tag_id){
		    $tag->setInc('num','tag_id='.$tag_id); ;
			return $tag_id;
		}else{
			$map['tag_name']  = $tagname;
			$map['num']       = 1;
			$map['recommend'] = 0;
			$tag_id=$tag->add($map);
			return $tag_id;
		}
		//echo $tag->getLastSql(); 
		
	}
	/*得到 文章的前 N个标签
	* $weibo_id    博客id
	* $limit      获取标签个数
	*/
	private function _gettag($weibo_id,$limit='') {
	   $db_prefix  =  C('DB_PREFIX');
	   $tag=M('');
	   $tag_names = $tag->field('t.tag_name')->table("{$db_prefix}weibo_tag AS wt LEFT JOIN {$db_prefix}tag AS t ON wt.tag_id=t.tag_id")
	         ->where('weibo_id='.$weibo_id)->limit($limit)->order('wt.tag_id ASC')->findAll();
			 //echo $tag->getLastSql();
	   return $tag_names;
	}
    private function __getSearchKey() {
		$key = '';
		// 为使搜索条件在分页时也有效，将搜索条件记录到SESSION中
		if (isset ( $_REQUEST ['k'] ) && ! empty ( $_REQUEST ['k'] )) {
			if ($_GET ['k']) {
				$key = html_entity_decode ( urldecode ( $_GET ['k'] ), ENT_QUOTES );
			} elseif ($_POST ['k']) {
				$key = $_POST ['k'];
			}
			// 关键字不能超过30个字符
			if (mb_strlen ( $key, 'UTF8' ) > 30)
				$key = mb_substr ( $key, 0, 30, 'UTF8' );
			$_SESSION ['home_user_search_key'] = serialize ( $key );
		
		} else if (is_numeric ( $_GET [C ( 'VAR_PAGE' )] )) {
			$key = unserialize ( $_SESSION ['home_user_search_key'] );
		
		} else {
			//unset($_SESSION['home_user_search_key']);
		}
		
		return trim ( $key );
	}	
}



?>